<template>
  <div v-loading="loading" class="app-main-content-box business-store-edit">
    <div class="instructions">
      <h3>说明</h3>
      <p>
        店铺数据同步来源于聚合支付超管数据配置，该数据同步类型为不可编辑，不支持店铺修改，如果需要修改，请到聚合支付。
      </p>
    </div>

    <app-main-title :title="type === 'edit' ? '修改店铺配置' : '新增店铺'" />
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="130px"
      class="demo-ruleForm"
    >
      <el-form-item v-if="type === 'edit'" label="店铺状态：">
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-tag>{{ form.disabled ? '关停中' : '启用中' }}</el-tag>
            <el-tag type="danger" style="margin-left: 10px">{{
              STATUS_TEXT[form.status]
            }}</el-tag>
          </div>
          <div>
            <el-button
              type="danger"
              @click="onClickStopStore"
            >{{ form.disabled ? '启用' : '关停' }}店铺</el-button>
            <el-button
              v-if="!form.disabled"
              @click="onClickCloseStore"
            >{{ form.status === 0 ? '营业' : '打烊' }}
            </el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="店铺全称：" prop="fullName">
        <el-input
          v-model="form.fullName"
          placeholder="请输入"
          :disabled="form_disabled"
        />
      </el-form-item>
      <el-form-item label="店铺简称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入" />
      </el-form-item>

      <el-form-item prop="openTimeType" label="类型">
        <el-radio-group v-model="form.openTimeType" class="open_type">
          <el-radio
            :label="1"
          >营业时间
            <el-tooltip
              class="item"
              effect="dark"
              content="营业时间为商户24h内设置的店铺营业时间，不设置的时间为店铺非营业时间"
              placement="top"
            >
              <span class="el-icon-question" />
            </el-tooltip>
          </el-radio>
          <el-radio :label="2">
            非营时间
            <el-tooltip
              class="item"
              effect="dark"
              content="非营业时间为商户24h内设置的店铺非营业时间，不设置的时间为店铺营业时间"
              placement="top"
            >
              <span class="el-icon-question" />
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="营业时间：" prop="customParamsOpenTime">
        <el-time-picker
          v-model="form.customParamsOpenTime"
          is-range
          value-format="HH:mm"
          format="HH:mm"
          range-separator="~"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
        />
      </el-form-item>

      <el-form-item label="支付方式" prop="payChannels">
        <div>
          <el-checkbox-group v-model="form.payChannels">
            <el-checkbox
              v-for="(v, k, i) in payChannelsOptions"
              :key="i"
              :label="k"
            >{{ v }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>

      <el-form-item label="店铺LOGO：" prop="icon">
        <el-upload
          class="app-uploader-img-plus fl"
          :action="actionUrl"
          :show-file-list="false"
          :headers="uploadHeaders"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.icon" :src="fileBaseUrl + form.icon" class="avatar">
          <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
        </el-upload>
        <ul class="fl upload_tips">
          <li>图片要求：</li>
          <li>1.上传的图片限制文件大小不超过500KB，仅支持JPG/PNG格式</li>
          <li>2.像素大小控制在300像素*300像素以下</li>
          <li>
            <el-button
              size="small"
              round
              @click="openCardImgMap"
            >从系统图库中选择</el-button>
          </li>
        </ul>
      </el-form-item>

      <el-form-item label="店铺图片：" prop="imageList">
        <div class="img-list-container">
          <draggable
            :list="form.imageList"
            :options="{ filter: '.undrag' }"
            style="display: flex; flex-wrap: wrap"
          >
            <div
              v-for="(v, i) in form.imageList"
              :key="i"
              class="img-item drag"
            >
              <img :src="v.url" alt class="imgs">
              <div class="handle-icon">
                <i class="el-icon-zoom-in icon" @click="handlePreview(v)" />
                <i class="el-icon-delete icon" @click="handleImgRemove(v, i)" />
              </div>
            </div>

            <div class="img-item undrag">
              <el-upload
                :limit="10"
                :action="actionUrl"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :file-list="form.imageList"
                :before-upload="handleImgBefore"
                :on-success="handleImgSuccess"
                :on-exceed="handleImgExceed"
                drag
                multiple
                :show-file-list="false"
                list-type="picture-card"
                class="upload-container"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
              <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
                <img width="100%" :src="dialogImageUrl" alt>
              </el-dialog>
            </div>
          </draggable>
        </div>
        <div class="upload-tips">
          <div>1.只能上传jpg/png文件，且不超过1mb</div>
          <div>2.建议尺寸1060*530像素，最多上传10张</div>
          <div>3.可长按图片进行拖拽排序</div>
        </div>
      </el-form-item>

      <el-form-item label="联系电话：" prop="mobilePhone">
        <el-input
          v-model="form.mobilePhone"
          placeholder="请输入"
          :disabled="form_disabled"
        />
      </el-form-item>
      <el-form-item label="客服电话：" prop="servicePhone">
        <el-input v-model="form.servicePhone" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="店铺地址：" prop="address">
        <el-form-item prop="provinceCode">
          <el-cascader
            v-model="selectedOptions"
            class="input-width-250"
            size="small"
            :options="options"
            @change="handleChooseAddressChange"
			:props="props"
          />
        </el-form-item>
        <el-input
          v-model="form.address"
          type="textarea"
          :autosize="{ minRows: 2 }"
          placeholder="请输入详细地址"
        />
      </el-form-item>

      <el-form-item label="店铺位置：" prop="latitude">
        <TencentMap
          :tencent-map-src="tencentMapSrc"
          @getPackingLocation="getPackingLocation"
        />
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="form.landmark"
          maxlength="20"
          show-word-limit
          placeholder="可输入地标，方便用户导航，如某某地铁出口，右转100m"
        />
      </el-form-item>
      <el-form-item
        label="店铺分享文案设置："
        label-width="160"
        prop="shareText"
      >
        <el-input v-model="form.shareText" placeholder="请输入" />
        <div class="default_msg">默认：新注册会员获取更多优惠</div>
      </el-form-item>
      <el-form-item label="店铺描述：" prop="description">
        <el-input
          v-model="form.description"
          placeholder="请输入"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="店铺公告：" prop="shopNotice">
        <el-input
          v-model="form.shopNotice"
          placeholder="请输入"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <div class="foot">
      <div>
        <el-button type="primary" size="medium" round @click="onSubmit('form')">{{ type === 'edit' ? '提交' : '创建' }}
        </el-button>
        <el-button size="medium" round @click="routerBack()">取消</el-button>
      </div>
    </div>
    <!-- 图库 -->
    <card-img-map ref="cardImgMap" img-type="LOGO" />
  </div>
</template>
<script>
const STATUS = {
  // status 0:已打烊  1:正常营业  2:部分营业
  CLOSED: 0,
  NORMAL: 1,
  PARTIAL: 2
}
const STATUS_TEXT = {
  [STATUS.CLOSED]: '已打烊',
  [STATUS.NORMAL]: '正常营业',
  [STATUS.PARTIAL]: '部分营业'
}
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import { getArea } from '@/api/shop'
import { validateAllPhone, validateStrLen } from '@/utils/validate.js'
import {
  getShopInfo,
  createShop,
  updateShop,
  updateShopStatus
} from '@/api/shop'
import TencentMap from '@/components/TencentMap/TencentMap'
import draggable from 'vuedraggable'
let initProvinceCode = ''
export default {
  components: {
    TencentMap,
    draggable
  },
  props: {
    type: {
      require: true,
      type: String,
      default: ''
    },
    id: {
      require: true,
      type: [String, Object],
      default: ''
    }
  },
  data() {
    /**
     * 表单校验方法相关
     */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入简称'))
      } else if (!validateStrLen(value, 24)) {
        callback(new Error('长度不超过12个汉字或24个字符'))
      } else {
        callback()
      }
    }
    const validateNameKey = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入简称'))
      } else if (!validateStrLen(value, 200)) {
        callback(new Error('长度不超过200个汉字或400个字符'))
      } else {
        callback()
      }
    }
    const validateTelPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入联系电话'))
      } else if (!validateAllPhone(value)) {
        callback(
          new Error(
            '请输入手机号或固话(格式：8888888、020-8888888、(020)8888888'
          )
        )
      } else {
        callback()
      }
    }
    const validateAddress = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入店铺地址'))
      } else if (!validateStrLen(value, 200)) {
        callback(new Error('长度不超过100个汉字或200个字符'))
      } else {
        callback()
      }
    }
    return {
      /**
       * 表单校验字段相关
       */
      rules: {
        // Logo图
        icon: [
          {
            required: true,
            message: '请上传店铺LOGO图',
            trigger: ['change']
          }
        ],
        // 名称
        // 名称
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        description: [
          {
            required: true,
            validator: validateNameKey,
            trigger: ['blur', 'change']
          }
        ],
        shopNotice: [
          {
            required: true,
            validator: validateNameKey,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        fullname: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        // 手机号
        mobilePhone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        servicePhone: [
          {
            required: true,
            validator: validateTelPhone,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        address: [
          {
            required: true,
            validator: validateAddress,
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        latitude: [
          {
            required: true,
            message: '请选择店铺所在位置',
            trigger: ['blur', 'change']
          }
        ],
        customParamsOpenTime: [
          { required: true, message: '请选择营业时间', trigger: 'change' }
        ],
        // 支付方式
        payChannels: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一种支付渠道'
          }
        ],
        imageList: {
          type: 'array',
          required: true,
          message: '请上传店铺图片',
          trigger: ['change']
        }
      },
      loading: false,
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      payChannelsOptions: { 0: '微信支付', 1: '会员钱包' },
      form: {
        icon: '',
        name: '',
        fullName: '',
        mobilePhone: '',
        servicePhone: '',
        address: '',
        landmark: '',
        latitude: '',
        longitude: '',
        provinceCode: '',
        cityCode: '',
        description: '',
        shopNotice: '',
        areaCode: '',
        shareText: '',
        openTimeType: 1, // 营业时间标识 1 代表营业时间 2代表非营业时间
        customParamsOpenTime: '',
        payChannels: [],
        imageList: []
      },
      form_disabled: false,
      /* 地图（腾讯和高德）*/
      chooseAddr: {},
      mapSrc: '',
      tencentMapSrc: '', // 腾讯地图地址
      options: '',
      selectedOptions: ['广东省','广州市','荔湾区'], // 选择的地址默认
      STATUS_TEXT,
      dialogImageVisible: false,
      dialogImageUrl: '',
	  // 省市区
	  props: {
		lazy: true,
		lazyLoad (node, resolve) {
		  let that = this
		  const { level,label } = node;
		  setTimeout(() => {
			if(level === 1){
				// 加载市
				node.children = [] //防止加载重复数据
				this.provinceName = label
				let data = {
				  provinceName:label,
				  type:2,
				}
				getArea(data).then(res => {
					resolve(res.data);
				})
			}else if(level === 2){
				// 加载区
				node.children = []
				let data = {
				  provinceName:this.provinceName || initProvinceCode,
				  code:label,
				  type:3
				}
				getArea(data).then(res => {
					res.data.forEach(el => {
						el.leaf = level >= 2 //取消最后一级箭头
					})
					resolve(res.data);
				})
			}
		  }, 100);
		}
	  }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userInfo'])
  },
  created() {
    this.id = JSON.parse(this.$route.params.id)
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    onClickStopStore() {
      const text = this.form.disabled ? '启用' : '关停'
      this.$confirm(
        `您确定${text}门店佛山市禅城区陈阳大厦”的所有服务?包括商城、餐饮、服务、场所等。`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async() => {
        const { code } = await updateShopStatus({
          disabled: !this.form.disabled,
          shopId: this.id.id // 传参现在id是个对象了，没改名字是因为用的动态路由传参所以为了方便不改路由配置而继续使用id名
        })
        if (code === 0) {
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.fetchData()
        }
      })
    },
    onClickCloseStore() {
      const text = this.form.status === 0 ? '关闭打烊' : '打烊'
      this.$confirm(
        `您确定${text}门店“佛山市禅城区陈阳大厦”的所有服务?包括商城、餐饮、服务、场所等。`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async() => {
        const { code } = await updateShopStatus({
          shopId: this.id.id,
          status: this.form.status === 0 ? 1 : 0
        })
        if (code === 0) {
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.fetchData()
        }
      })
    },
    // 上传图片
    handleImgBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },

    handleImgSuccess(res, file, fileList) {
      if (res.code === 0) {
        this.form.imageList = fileList
        this.$refs.form.clearValidate(['imageList'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleImgRemove(v, i) {
      this.form.imageList.splice(i, 1)
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    handleImgExceed() {
      this.$message.error('最多上传10张')
    },
    /**
     * 获取数据
     */
    // 获取店铺信息
    fetchData() {
      // 设置修改权限
      const syncTmpMerchantId = this.userInfo.business.syncTmpMerchantId
      if (syncTmpMerchantId) {
        this.form_disabled = true
      } else {
        this.form_disabled = false
      }

      if (this.type === 'edit') {
        getShopInfo(this.id.id).then((res) => {
          const { openHour, openMin, closeHour, closeMin, payChannels,provinceCode,cityCode,areaCode } =
            res.data
          res.data.customParamsOpenTime = [
            `${openHour}:${openMin}`,
            `${closeHour}:${closeMin}`
          ]
          res.data.payChannels = payChannels.split(',')
          if (!res.data.imageList) res.data.imageList = []
          res.data.imageList = res.data.imageList.map((v) => {
            return {
              response: { code: 0, data: { path: v } },
              url: this.fileBaseUrl + v
            }
          })
          this.form = res.data
          // 腾讯地图和高德地图设置
          this.tencentMapSrc = `https://apis.map.qq.com/tools/locpicker?coord=${
            res.data.longitude ? res.data.longitude : 113.258339809
          },${
            res.data.latitude ? res.data.latitude : 23.149134849
          }&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18`
          // 地址选择默认值处理
          if (this.form.provinceCode) {
			this.getProvinceFunc(provinceCode,cityCode,areaCode)
          }
        })
      } else {
        // add
        this.handleChooseAddressChange(this.selectedOptions)
        this.tencentMapSrc = `https://apis.map.qq.com/tools/locpicker?coord=113.258339809,23.149134849&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18`
      }
    },

    /**
     * 按钮组
     */
    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 300, 300, 0.5)
    },
    // 提交
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = Object.assign({}, this.form)
          params.payChannels = params.payChannels.join(',')
          // 格式化时间
          const openTime = params.customParamsOpenTime[0].split(':')
          const closeTime = params.customParamsOpenTime[1].split(':')
          params.openHour = openTime[0]
          params.openMin = openTime[1]
          params.closeHour = closeTime[0]
          params.closeMin = closeTime[1]
          params.imageList = params.imageList.map((v) => {
            if (
              v.response &&
              v.response.code === 0 &&
              v.response.data &&
              v.response.data.path
            ) {
              return v.response.data.path
            }
          })
          delete params.customParamsOpenTime
          this.loading = true
          if (this.type === 'add') {
            createShop(params)
              .then((res) => {
                if (res.code === 0) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000,
                    offset: 40
                  })
                  this.loading = false
                  this.$store.dispatch('GetManageShop')
                  this.$router.push({ name: 'BusinessInfo' })
                } else {
                  this.loading = false
                  this.$message.error(res.msg)
                }
              })
              .finally(() => {
                this.loading = false
              })
          } else if (this.type === 'edit') {
            updateShop(params)
              .then((res) => {
                if (res.code === 0) {
                  this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000,
                    offset: 40
                  })
                  this.loading = false
                  this.$store.dispatch('GetManageShop')
                  this.$router.push({ name: 'BusinessInfo' })
                } else {
                  this.loading = false
                  this.$message.error(res.msg)
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        } else {
          return false
        }
      })
    },
    // 取消
    routerBack() {
      this.$router.push({ name: 'BusinessInfo' })
    },
    // 打开图库
    openCardImgMap() {
      this.$refs.cardImgMap.open().then((res) => {
        this.form.icon = res
      })
    },
    // 地图选择
    getPackingLocation(addrLocation) {
      this.form.latitude = addrLocation.latlng.lat
      this.form.longitude = addrLocation.latlng.lng
      this.$refs.form.clearValidate(['latitude'])
    },
		
	// 初始默认赋值 - 省市区
	getProvinceFunc(lable,cityCode,areaCode){
		// 请求省
		let data = { type: 1 }
		let provinceList = ''
		getArea(data).then(res => {
			provinceList = res.data
			// 请求市
			let data = {
			  provinceName: lable,
			  type:2
			}
			let provinceIndex = ''
			provinceList.forEach((el,index) => {
				if(el.label === lable){
					provinceIndex = index
				}
			})
			getArea(data).then(res => {
			    provinceList[provinceIndex].children = res.data
				let data = {
				  provinceName:lable,
				  code:cityCode,
				  type:3
				}
				let cityIndex = ''
				provinceList[provinceIndex].children.forEach((el,index) => {
					if(el.label === cityCode){
						cityIndex = index
					}
				})
				// 请求区
				getArea(data).then(res => {
					res.data.forEach(el => {
						el.leaf = true //回显必填
					})
					provinceList[provinceIndex].children[cityIndex].children = res.data //某个市children
					this.options = provinceList
					// 设置值
					initProvinceCode = lable //设置默认的省
					this.selectedOptions = [lable,cityCode,areaCode]
				})
			})
		})
	},
	handleChooseAddressChange(value) {
	  console.log('value',value)
	  this.form.provinceCode = value[0]
	  this.form.cityCode = value[1]
	  this.form.areaCode = value[2]
	},
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.business-store-edit {
  position: relative;
  .instructions {
    border: 1px solid #dcdfe6;
    padding: 16px;
    box-sizing: border-box;
    margin: 15px 0 50px;
    h3 {
      margin-bottom: 16px;
      font-size: 1.17em;
      font-weight: 500;
    }
    p {
      font-weight: 200;
    }
  }

  .img-item {
    width: 15%;
    margin-right: 20px;
    margin-top: 20px;
  }

  .default_msg {
    margin-left: 140px;
    color: #9e9e9e;
    font-size: 12px;
  }
  .el-input,
  .el-textarea {
    width: 70%;
    max-width: 600px;
  }

  .app-uploader-img-plus {
    width: 180px;
    height: 180px;

    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 180px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }
    .avatar {
      width: 180px;
      height: 180px;
      display: block;
    }
  }

  .upload_tips {
    margin: 20px 0 0 20px;

    li {
      margin-top: 10px;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
}

.img-list-container {
  width: 100vw;
  .drag {
    position: relative;
  }

  .imgs {
    min-width: 200px;
    min-height: 200px;
    object-fit: cover;
  }

  .handle-icon {
    position: absolute;
    top: -10px;
    right: 2px;
  }
}

.upload-tips {
  div {
    color: $dark-font-color;
  }
}

.foot {
  width: 150px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  position: fixed;
  left: 50%;
  bottom: 20px;
  z-index: 99;
  // background-color: #ffffff;
  // box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
</style>
